package com.njupt.Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MergeIntervals_56 {

    public int[][] merge(int[][] intervals) {
        List<int[]> results = new ArrayList<>();

//        int[][] array = Arrays.stream(intervals).sorted((v1, v2) -> {
//            return v1[0] - v2[0];
//        }).toArray(int[][]::new);

        Arrays.sort(intervals,(v1,v2)->{
            return v1[0] - v2[0];
        });

        for(int i = 0;i < intervals.length;i++){
            int left = intervals[i][0];
            int right = intervals[i][1];

            if(results.size() == 0 || results.get(results.size()- 1)[1] < left){
                results.add(new int[]{left,right});
            }else {
                results.get(results.size()- 1)[1] = Math.max(results.get(results.size()- 1)[1],right);
            }
        }

        return results.toArray(new int[results.size()][]);
    }


    public static void main(String[] args) {
        int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
        MergeIntervals_56 test = new MergeIntervals_56();
        int[][] merge = test.merge(intervals);
        for(int i = 0 ; i < merge.length; i++){
            for(int j = 0;j < intervals[i].length;j++){
                System.out.print(merge[i][j] + " ");
            }
            System.out.println();
        }
    }
}
